package com.samxcode.leetcode;

/**
 * Implement atoi to convert a string to an integer.
 * 
 * @author Sam
 *
 */
public class StringToInteger {
    
    public static void main(String[] args) {
        System.out.println(atoi("    010"));
        
    }

    public static int atoi(String str) {
        int len = str.length();
        int result = 0;
        int index = 0;
        boolean negative = false;
        int limit = Integer.MAX_VALUE;
        int multimin;
        int diff;
        char ch;
        while (index < len && str.charAt(index) == ' ') {
            index++;
        }
        if (len > 0) {
            char firstChar = str.charAt(index);
            if (firstChar < '0') {
                if (firstChar == '-') {
                    negative = true;
                } else if (firstChar != '+') {
                    return 0;
                }
                index++;
            }
            multimin = limit / 10;
            while (index < len) {
                ch = str.charAt(index);
                if (ch < '0' || ch > '9') {
                    return negative ? -result : result;
                }
                diff = ch - '0';
                if (result > multimin || result == multimin && diff > limit % 10) {
                    return negative ? Integer.MIN_VALUE : limit;
                }
                result = result * 10 + diff;                
                index++;
            }
        }
        return negative ? -result : result;
    }
}
